<?php

include dirname(__FILE__) . '/../../class/_core.php';
include dirname(__FILE__) . '/../../class/department.php';

$department = new department();
$view = $department->department_view_all();

$from = $_GET['from'];
$to = $_GET['to'];

if ($from != "" && $to != "") {
    foreach ($view as &$v) {
        $text = "SELECT
	product_model,
	fac_product_mess.product_id,
	SUM(fac_department_product_record.number) AS numberX,
        (SELECT SUM(number) FROM fac_department_receive_record WHERE department_id = $v[department_id] AND product_id = fac_product_mess.product_id AND create_time>='$from' AND create_time<='$to') AS getX
FROM
	fac_department_product_record
LEFT JOIN `fac_product_mess` on fac_department_product_record.product_id = fac_product_mess.product_id
WHERE
	department_id = $v[department_id]  AND create_time>='$from' AND create_time<='$to'
GROUP BY
	product_id ORDER BY numberX DESC";
        $v['produce'] = Db::get_instance()->query($text);
        ;
        foreach ($v['produce'] AS &$p) {
            if($p['getX'] == NULL || $p['numberX'] == NULL){
                $p['rate'] = false;
            } else {
                $p['rate'] = round(($p['numberX'] / $p['getX']) * 100, 2);
            }
        }
    }
} else {
    foreach ($view as &$v) {
        $text = "SELECT
	product_model,
	fac_product_mess.product_id,
	SUM(fac_department_product_record.number) AS numberX,
        (SELECT SUM(number) FROM fac_department_receive_record WHERE department_id = $v[department_id] AND product_id = fac_product_mess.product_id ) AS getX
FROM
	fac_department_product_record
LEFT JOIN `fac_product_mess` on fac_department_product_record.product_id = fac_product_mess.product_id
WHERE
	department_id = $v[department_id] 
GROUP BY
	product_id ORDER BY numberX DESC";
        $v['produce'] = Db::get_instance()->query($text);
        ;
        foreach ($v['produce'] AS &$p) {
            if($p['getX'] == NULL || $p['numberX'] == NULL){
                $p['rate'] = false;
            } else {
                $p['rate'] = round(($p['numberX'] / $p['getX']) * 100, 2);
            }
        }
    }
}

$Smarty->assign('dept', $view);
$Smarty->display('department/department_status.tpl');
